package com.syx.gateway.Filter;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.syx.common.redis.Service.RedisService;
import com.syx.commoncore.Constant.CacheConstant;
import com.syx.commoncore.Constant.Constant;
import com.syx.commoncore.Constant.Constants;
import com.syx.commoncore.Constant.HttpConstants;
import com.syx.commoncore.Model.Result;
import com.syx.commoncore.Utils.ThreadLocalUtil;
import com.syx.commoncore.enums.Resultcode;
import com.syx.commoncore.enums.UserIdEnum;
import com.syx.gateway.properties.IgnoreWhiteProperties;

import com.syx.commoncore.Utils.JwtUtils;
import com.syx.commoncore.Model.LoginUser;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
//身份认证主逻辑，全局过滤器，请求转发给相应的服务前先做什么工作，order会返回一个int顺序，表明全局过滤器的顺序
public class AuthFilter implements GlobalFilter, Ordered {
    // 排除过滤的 uri ⽩名单地址，在nacos⾃⾏添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Value("${jwt.secret}")
    private String secret;
    @Autowired
    private RedisService redisService;
    //具体做什么
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain
            chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //请求接口 ，除了登录接口
        String url = request.getURI().getPath();

        // 跳过不需要验证的路径，接口白名单，都不需要校验
        if (matches(url, ignoreWhite.getWhites())) {//判断当前的接口在不在白名单中，在的话不需要身份认证，拿到nacos上面的白名单
            //不需要校验
            return chain.filter(exchange);
        }
        //从http请求头中获取token
        String token = getToken(request);
        //没有token
        if (StrUtil.isEmpty(token)) {
            //无法使用throw 异常的方法
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        Claims claims;
        try {
            //拿到token进行解析
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息，也就是唯一身份标识
            if (claims == null) {
                //解析失败，可能secret改变解析不出来
                //如果token过期之后，也就不存在客户端了，那就会过期并且为空
                return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
            }
        } catch (Exception e) {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }
        /*log.warn(claims.toString());*/
        //uuid随机生成的key
        String userKey = JwtUtils.getUserKey(claims); //获取jwt中的key
        boolean isLogin = redisService.hasKey(getTokenKey(userKey));
        if (!isLogin) {
            return unauthorizedResponse(exchange, "登录状态已过期");
        }
        String userId = JwtUtils.getUserId(claims); //判断jwt中的信息是否完整
        if (StrUtil.isEmpty(userId)) {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }
        //判断成功代码redis中存在数据，并且没有过期
        LoginUser user = redisService.getCacheObject(getTokenKey(userKey),
                LoginUser.class);
        //判断B端用户
        if (url.contains(HttpConstants.SYSTEM_URL_PREFIX) &&
                !UserIdEnum.ADMIN.getValue().equals(user.getIdentity())) {
            return unauthorizedResponse(exchange, "令牌验证失败您不是管理员");
        }
        //判断c端用户
        if (url.contains(HttpConstants.FRIEND_URL_PREFIX) &&
                !UserIdEnum.ORDINARY.getValue().equals(user.getIdentity())) {
            return unauthorizedResponse(exchange, "令牌验证失败您不是普通用户");
        }

        //将userId存入，也将tokenKey放入


        return chain.filter(exchange);
    }
    /**
     * 查找指定url是否匹配指定匹配规则链表中的任意⼀个字符串
     *
     * @param url 指定url
     * @param patternList 需要检查的匹配规则链表
     * @return 是否匹配
     */
    //遍历完如果成功匹配就返回true都没有匹配返回false；
    private boolean matches(String url, List<String> patternList) {
        if (StrUtil.isEmpty(url) || CollectionUtils.isEmpty(patternList)) {
            return false;
        }
        for (String pattern : patternList) {
            if (isMatch(pattern, url)) {
                return true;
            }
        }
        return false;
    }
    /**
     * 判断url是否与规则匹配
     * 匹配规则中：
     * ? 表⽰单个字符;
     * * 表⽰⼀层路径内的任意字符串，不可跨层级;
     * ** 表⽰任意层路径;
     *
     * @param pattern 匹配规则
     * @param url 需要匹配的url
     * @return 是否匹配
     */
    private boolean isMatch(String pattern, String url) {
        AntPathMatcher matcher = new AntPathMatcher();
        return matcher.match(pattern, url);
    }
    /**
     * 获取缓存key
     */
    private String getTokenKey(String token) {
        return CacheConstant.LOGIN_TOKEN_KEY + token;
    }
    /**
     * 从请求头中获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token =
                request.getHeaders().getFirst(HttpConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) &&
                token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return token;
    }
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String
            msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return webFluxResponseWriter(exchange.getResponse(), msg,
                Resultcode.FAILED_UNAUTHORIZED.getCode());
    }
    //拼装webflux模型响应
    private Mono<Void> webFluxResponseWriter(ServerHttpResponse response,
                                             String msg, int code) {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE,
                MediaType.APPLICATION_JSON_VALUE);
        Result<?> result = Result.failure(code, msg);
        DataBuffer dataBuffer =
                response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
    @Override
    public int getOrder() {
        //值越小越先被执行
        return -200;
    }
    //1.登录成功后使用createToken创建令牌，发给用户
    //2.后续所有请求请求之前先使用token
    //3，需要适当延长token时间



}

